import axios from 'axios'
import useUserStore from '../store/user'
import router from '@/router'
import { ElMessage } from 'element-plus'
// 请求封装
export const request=axios.create({
  baseURL:'/api',
  timeout:10000
})
// 请求拦截
request.interceptors.request.use((config) => {
  let userStore = useUserStore();
  if (userStore.userInfo?.token) {
    config.headers.token = userStore.userInfo.token
  }
  return config;
})
// 响应拦截
request.interceptors.response.use((response) => {
  let code=response.data.code
  switch(code){
    case "0":
      response.data.code=0
      break;
    case "A000203":
      useUserStore().logout()
      ElMessage({
        message: '登录信息过期,准备前往登录界面',
        grouping:true,
        type: 'error'
      })
      router.push('/login')
      break;
    default:
      response.data.code=2
      ElMessage({
        type: 'error',
        message: response.data.message
      })
  }
  return response.data
}, (error) => {
  let status = error.response.status;
  switch (status) {
    case 404:
      ElMessage({
        type: 'error',
        message: error.message
      })
      break;
    case 500 | 501:
      ElMessage({
        type: 'error',
        message: "服务器异常"
      })
  }
  return Promise.reject(new Error(error.message))
})